package com.myrpc.proxy;

import com.myrpc.transfer.transport.RpcRequestTransport;
import com.myrpc.transfer.transport.socket.SocketRpcRequestClient;
import net.sf.cglib.proxy.Enhancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

/**
 * 代理对象创建工厂
 */
@Component
@DependsOn({"SocketRpcRequestClient"})
public class CglibProxyFactory {

    @Autowired
    public RpcRequestTransport rpcRequestTransport;
    /**
     * 得到某个类的代理对象
     * @param clazz 代理对象的运行时类对象
     * @return 代理对象
     */
    public <T> T getProxy(Class<T> clazz){
        //创建动态代理增强类
        Enhancer enhancer = new Enhancer();
        //设置类加载器
        enhancer.setClassLoader(clazz.getClassLoader());
        //设置被代理类
        enhancer.setSuperclass(clazz);
        //设置方法拦截器
        enhancer.setCallback(new RemoteMethodInterceptor(this.rpcRequestTransport));
        //创建代理对象
        return (T) enhancer.create();
    }
}
